<!--调拨统计-->
<template>
  <div class="total-purchase">
    <!-- 时间筛选 -->
    <!-- 修改 @tab-click 以传递 tab 的 name -->
    <el-tabs v-model="activeTime" class="time-tabs" @tab-click="tab => handleTimeTabClick(tab)">
      <el-tab-pane label="今日" name="today"></el-tab-pane>
      <el-tab-pane label="昨日" name="yesterday"></el-tab-pane>
      <el-tab-pane label="本周" name="week"></el-tab-pane>
      <el-tab-pane label="上周" name="lastWeek"></el-tab-pane>
      <el-tab-pane label="本月" name="month"></el-tab-pane>
      <el-tab-pane label="上月" name="lastMonth"></el-tab-pane>
    </el-tabs>
    <!-- 查询条件 -->
    <el-form label-width="100px" :inline="true" class="demo-form-inline" ref="searchref">
      <!-- 第一行 -->
      <div class="form-row">
        <el-form-item label="货品" prop="proc_code">
          <el-input v-model="searchform.proc_code" placeholder="请输入货物名称/编号"></el-input>
        </el-form-item>
        <el-form-item label="调拨单号" prop="al_code">
          <el-input v-model="searchform.al_code" placeholder="请输入调拨单号" style="width:200px;"></el-input>
        </el-form-item>
        <el-form-item label="调拨类型" prop="al_type">
          <el-select v-model="searchform.al_type" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in allotTypes" 
              :key="item.bus_id" 
              :label="item.bus_name" 
              :value="item.bus_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="制单人" prop="header_create_by">
          <el-select v-model="searchform.header_create_by" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in users" 
              :key="item.user_id" 
              :label="item.user_name" 
              :value="item.user_id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- 第二行 -->
      <div class="form-row">
        <el-form-item label="货品类型" prop="type_id">
          <el-select v-model="searchform.type_id" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in productTypes" 
              :key="item.type_id" 
              :label="item.type_name" 
              :value="item.type_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="proc_primary_unit">
          <el-select v-model="searchform.proc_primary_unit" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in units" 
              :key="item.dict_value" 
              :label="item.dict_label" 
              :value="item.dict_label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="al_user">
          <el-select v-model="searchform.al_user" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in users" 
              :key="item.user_id" 
              :label="item.user_name" 
              :value="item.user_id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- 第三行 -->
      <div class="form-row">
        <el-form-item label="调入仓库" prop="in_wh_id">
          <el-select v-model="searchform.in_wh_id" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in warehouses" 
              :key="item.wh_id" 
              :label="item.wh_name" 
              :value="item.wh_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调出仓库" prop="out_wh_id">
          <el-select v-model="searchform.out_wh_id" placeholder="请选择" style="width:200px;">
            <el-option 
              v-for="item in warehouses" 
              :key="item.wh_id" 
              :label="item.wh_name" 
              :value="item.wh_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调拨日期" prop="date">
          <el-date-picker 
            v-model="searchform.date"
            type="datetimerange" 
            format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 350px;" 
          />
        </el-form-item>
      </div>
      <!-- 第四行：出入库状态 -->
      <div class="form-row">
        <el-form-item label="出入库状态" prop="stockStatus">
            <!-- 入库状态 -->
            <div>
              <el-checkbox-group v-model="searchform.instock_status" style="display: inline-block; margin-left: 10px;">
                  <el-checkbox 
                  v-for="item in instockstatusdata" 
                  :key="item.dict_value" 
                  :label="item.dict_value"
                  style="margin-right: 20px;"
                  >
                  {{ item.dict_label }}
                  </el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- 出库状态 -->
            <div>
              <el-checkbox-group v-model="searchform.outstock_status" style="display: inline-block; margin-left: 10px;">
                  <el-checkbox 
                  v-for="item in outstockstatusdata" 
                  :key="item.dict_value" 
                  :label="item.dict_value"
                  style="margin-right: 20px;"
                  >
                  {{ item.dict_label }}
                  </el-checkbox>
              </el-checkbox-group>
            </div>
        </el-form-item>
      </div>
      <!-- 第五行：重置和查询按钮 -->
      <div class="form-row">
        <el-form-item>
          <el-button @click="Reset">重置</el-button>
          <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
      </div>
    </el-form>
    <!-- 统计数据 -->
    <div class="statistics-container">
      <div class="stat-group">
          <div class="stat-item">
              <h3>{{ ATotal.totalRecordsH }}</h3>
              <p>调拨单数量</p>
          </div>
      </div>
      <div class="stat-group">
          <div class="stat-item">
              <h3>{{ ATotal.totalRecordsD }}</h3>
              <p>调拨货品数量</p>
          </div>
          <div class="stat-item">
              <h3>{{ ATotal.totalSum }}</h3>
              <p>调拨产品金额</p>
          </div>
      </div>
    </div>
    <!-- 导出和刷新按钮 -->
    <div class="action-buttons">
      <el-button @click="Export">导出</el-button>
    </div>
    <el-table 
      :data="displayData" 
      :border="true" 
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <!-- 主表列保持不变 -->
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55" fixed></el-table-column>
      <el-table-column fixed prop="proc_code" label="货品编号" width="200"></el-table-column>
      <el-table-column fixed prop="product_name" label="货品名称" width="120"></el-table-column>
      <el-table-column fixed prop="al_date" label="调拨申请日期" width="200"></el-table-column>
      <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
      <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
      <el-table-column prop="type_name" label="货品类型" width="200"></el-table-column>
      <el-table-column prop="proc_primary_barcode" label="条码" width="200"></el-table-column>
      <el-table-column prop="out_wh_name" label="调出仓库" width="200"></el-table-column>
      <el-table-column prop="in_wh_name" label="调入仓库" width="200"></el-table-column>
      <el-table-column prop="ald_instockOK_num" label="调入数量" width="200"></el-table-column>
      <el-table-column prop="ald_total" label="调入金额" width="200"></el-table-column>
      <el-table-column prop="ald_outstockOK_num" label="调出数量" width="200"></el-table-column>
      <el-table-column prop="ald_total" label="调出金额" width="200"></el-table-column> 
      <el-table-column prop="outstock_name" label="出库状态" width="150"></el-table-column>
      <el-table-column prop="instock_name" label="入库状态" width="120"></el-table-column>
      <el-table-column prop="al_user" label="经办人" width="200"></el-table-column>
      <el-table-column prop="header_create_by" label="制单人" width="200"></el-table-column>
      <el-table-column prop="header_create_time" label="制单时间" width="200"></el-table-column>
    </el-table>
    <!-- 分页控件 -->
     <!-- 页码 -->
     <!-- 修正：将 :total 绑定到 total 变量 -->
     <el-pagination 
       :page-size="10" 
       :pager-count="11" 
       layout="prev, pager, next, jumper" 
       :total="rows" 
       @current-change="handlePageChange" 
       style="float:right;margin-top:20px" 
       >
     </el-pagination>
  </div>
</template>
<script>
import {ref,reactive,onMounted,computed} from 'vue'; // 移除了未使用的 computed
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由 (如果未使用，也可以移除)
import * as XLSX from 'xlsx';
import qs from 'qs';
export default {
setup(){
  //表格数据
      const tableData=ref([]);
      const currentPage = ref(1);
      const total = ref(0); // 保留，用于分页
      //时间筛选
      const activeTime=ref('today');
      //查询条件
      const searchref=ref(null);
      const searchform = reactive({
        proc_code: '',                // 货品编号/名称
        al_code: '',                  // 调拨单号
        al_type: '',                  // 调拨类型
        header_create_by: '',         // 制单人
        type_id: '',                  // 货品类型
        proc_primary_unit: '',        // 单位
        al_user: '',                  // 经办人
        in_wh_id: '',                 // 调入仓库
        out_wh_id: '',                // 调出仓库
        date: [null, null],           // 日期范围
        creates_date: [null, null],   // 日期范围
        instock_status: [],           // 入库状态
        outstock_status: []           // 出库状态
      });
      const instockstatusdata = ref([]);
      const outstockstatusdata = ref([]);
      const warehouses = ref([]);      // 仓库列表
      const productTypes = ref([]);    // 货品类型
      const allotTypes = ref([]);      // 调拨类型
      const units = ref([]);           // 单位列表
      const rows = ref(0);             // 总行数
      // 获取仓库列表
      function GetWarehouses() {
        http.get("/Warehouse/GetWarehouses")
          .then(res => {
            warehouses.value = res.data;
          })
          .catch(err => {
            console.log(err);
            ElMessage.error('仓库加载失败');
          });
      }
      // 获取货品类型
      function GetProductTypes() {
        http.get("/ProductType/GetAllProductTypes")
          .then(res => {
            productTypes.value = res.data;
          })
          .catch(err => {
            console.log(err);
            ElMessage.error('货品类型加载失败');
          });
      }
      // 获取调拨类型
      function GetAllotTypes() {
        http.get("/BusinessType/GetBusinessTypes", {
          params: { field: '调拨' }
        })
        .then(res => {
          allotTypes.value = res.data;
        })
        .catch(err => {
          console.log(err);
          ElMessage.error('调拨类型加载失败');
        });
      }
      // 获取单位列表
      function GetUnits() {
        http.get("/DictData/GetAllDictDataBytype", {
          params: { typeid: 8 } // 8是单位的字典ID
        })
        .then(res => {
          units.value = res.data;
          console.log('单位',units.value);
        })
        .catch(err => {
          console.log(err);
          ElMessage.error('单位加载失败');
        });
      }
      //查询出入库状态 - 入库
      function instockstatus() {
        http.get("/DictData/GetAllDictDataBytype", {
            params: {
              typeid: 15
            }
        }).then(res => {
            console.log("入库:", res.data); // 调试用
            instockstatusdata.value = res.data;
        }).catch(err => {
            console.log(err);
            ElMessage.error('数据加载失败');
        });
      }
      //查询出入库状态 - 出库
      function outstockstatus() {
        http.get("/DictData/GetAllDictDataBytype", {
            params: {
              typeid: 14
            }
        }).then(res => {
            console.log("出库:", res.data); // 调试用
            outstockstatusdata.value = res.data;
        }).catch(err => {
            console.log(err);
            ElMessage.error('数据加载失败');
        });
      }

      //查询统计总量
      const ATotal=ref([]);

      // 查询数据
      function All() {
        // 处理日期范围
        const startTime = searchform.date && searchform.date[0] 
          ? new Date(searchform.date[0]).toISOString() : '';
        const endTime = searchform.date && searchform.date[1] 
          ? new Date(searchform.date[1]).toISOString() : '';

        const createsstartTime = searchform.creates_date && searchform.creates_date[0] 
          ? new Date(searchform.creates_date[0]).toISOString() : '';
        const createsendTime = searchform.creates_date && searchform.creates_date[1] 
          ? new Date(searchform.creates_date[1]).toISOString() : '';

        // 构建参数对象
        const params = {
          CurrentPage: currentPage.value,
          proc_code: searchform.proc_code,
          al_code: searchform.al_code,
          al_type: searchform.al_type,
          header_create_by: searchform.header_create_by,
          type_id: searchform.type_id,
          proc_primary_unit: searchform.proc_primary_unit,
          al_user: searchform.al_user,
          out_wh_id: searchform.out_wh_id,
          in_wh_id: searchform.in_wh_id,
          instock_status: searchform.instock_status,
          outstock_status: searchform.outstock_status,
          startTime: startTime,
          endTime: endTime,
          createstartTime: createsstartTime,
          createendTime: createsendTime
        };

        // 使用 qs 序列化参数（数组格式化为重复键名）
        const config = {
          params,
          paramsSerializer: params => 
            qs.stringify(params, { arrayFormat: 'repeat' })
        };

        // 同时发起两个请求
        Promise.all([
          http.get("/Allot_h/Gettotal", config),  // 总量请求
          http.get("/Allot_d/GetAllotTJResult", config)  // 明细请求
        ])
        .then(([summaryRes, detailRes]) => {
          // 处理总量数据
          ATotal.value = summaryRes.data; // 根据实际响应结构调整
          console.log("汇总数据:", ATotal.value);
          
          // 处理明细数据
          tableData.value = detailRes.data.list;
          total.value = detailRes.data.rows;
          console.log("明细数据:", tableData.value);
        })
        .catch(err => {
          console.error(err);
          ElMessage.error('数据加载失败');
        });
      }

      // 在 setup() 中添加
      const displayData = computed(() => {
          if (!outstockstatusdata.value.length || !instockstatusdata.value.length) {
              return []; // 基础数据未加载时返回空数组
          }
          
          return tableData.value.map(user => {
              // 查找入库状态名称
              const instock = instockstatusdata.value.find(
                  ins => ins.dict_value == user.detail_instock_status
              );
              
              // 查找出库状态名称
              const outstock = outstockstatusdata.value.find(
                  out => out.dict_value == user.detail_outstock_status
              );
              
              return {
                  ...user,
                  instock_name: instock?.dict_label || '未知入库状态',
                  outstock_name: outstock?.dict_label || '未知出库状态',
              };
          });
      });
      
      // 修改 Reset 函数，增加时间标签重置
      function Reset() {
        // 清空所有查询条件
        Object.keys(searchform).forEach(key => {
          if (Array.isArray(searchform[key])) {
            searchform[key] = [];
          } else {
            searchform[key] = '';
          }
        });
        Search();
      }

      // 查询
      function Search() {
        currentPage.value = 1; // 查询时重置到第一页
        All();
      }
      //查询所有用户
      const users=ref([]);
      function GetUsers(){
          return http.get("/User/GetAllUser")
          .then(res=>{
              users.value=res.data;
          }).catch(err=>{
              console.log(err);
          })
      }
      //查询统计总量
      function Gettotal(){
          return http.get("/Allot_h/Gettotal")
          .then(res=>{
            ATotal.value=res.data;
            console.log("Gettotal", res.data); // 修正日志
          }).catch(err=>{
              console.log(err);
          })
      }
      //分页
      function handlePageChange(page) {
        currentPage.value = page;
        All();
      }
      //时间筛选
      function handleTabChange(name) {
        activeTime.value =name;
        console.log(activeTime.value);
        currentPage.value = 1; // 切换时间筛选时重置到第一页
        All();
      }
      //选中的数据 (保留，因为导出功能依赖)
      const selectedRows = ref([]);
      function handleSelectionChange(selection) {
        selectedRows.value = selection;
      }

      //导出
      function Export() {
        // 如果没选中任何行，提示用户
        if (!selectedRows.value.length) { // <--- 修改点 1: 检查选中的行数组
          ElMessage.warning('请先选择要导出的单据！');
          return;
        }
        
        // 定义表头
        const header = [
          '货品编号', '货品名称', '调拨申请日期', '规格型号', '单位', '货品类型',
          '条码', '调出仓库', '调入仓库', '调入数量', '调入金额', '调出数量',
          '调出金额', '出库状态', '入库状态', '经办人', '制单人', '制单时间'
        ];
        
        // <--- 修改点 2: 遍历 selectedRows.value (选中的数据) 来生成导出数据
        const data = selectedRows.value.map(row => [ 
          row.proc_code, row.product_name, row.al_date, row.proc_model,
          row.proc_primary_unit, row.type_name, row.proc_primary_barcode,
          row.out_wh_name, row.in_wh_name, row.ald_instockOK_num,
          row.ald_total, row.ald_outstockOK_num, row.ald_total, // 调入调出金额同列?
          row.outstock_name, row.instock_name, // 使用 displayData 计算后的字段
          row.al_user, row.header_create_by, row.header_create_time
        ]);
        
        // 生成 worksheet 和 workbook
        const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '调拨统计');
        
        // 导出文件
        XLSX.writeFile(wb, '调拨统计.xlsx');
      }

      // 修改后的时间筛选功能
      function handleTimeTabClick(tab) {
        // 直接从事件参数获取当前点击的标签名
        const name = tab.props.name;
        
        const now = new Date();
        let start, end;

        switch (name) {
          case 'today': // 今天
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            break;
          case 'yesterday': // 昨天
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
            end = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            break;
          case 'week': // 本周
            const day = now.getDay() || 7;
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - day + 1);
            end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (7 - day) + 1);
            break;
          case 'lastWeek': // 上周
            const lastWeekDay = now.getDay() || 7;
            start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - lastWeekDay - 6);
            end = new Date(now.getFullYear(), now.getMonth(), now.getDate() - lastWeekDay + 1);
            break;
          case 'month': // 本月
            start = new Date(now.getFullYear(), now.getMonth(), 1);
            end = new Date(now.getFullYear(), now.getMonth() + 1, 1);
            break;
          case 'lastMonth': // 上月
            start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
            end = new Date(now.getFullYear(), now.getMonth(), 1);
            break;
          default:
            start = null;
            end = null;
        }

        // 设置日期范围
        searchform.creates_date = [start, end];
        
        // 立即执行查询
        Search();
      }

      //挂载
      onMounted(()=>{
        instockstatus();
        outstockstatus();
        GetWarehouses();
        GetProductTypes();
        GetAllotTypes();
        GetUnits();
        GetUsers(); // 确保获取用户数据
        activeTime.value = 'today';
        // 然后调用 handleTimeTabClick，传入代表 'today' 的 tab 名称
        // 为了使 handleTimeTabClick 能直接接收 name，我们稍微调整它的调用
        // 这里我们直接调用修改日期的逻辑部分
        const now = new Date();
        const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
        searchform.creates_date = [start, end]; // 设置为今天
        Search(); // 触发查询
      })
    return {
      // 返回给模板使用的变量和函数
      handleTimeTabClick,
      rows,
      displayData,
      warehouses,
      productTypes,
      allotTypes,
      units,
      searchform,
      ATotal,
      instockstatusdata,
      outstockstatusdata,
      tableData,
      currentPage,
      total, // 返回 total 供分页使用
      activeTime,
      searchref,
      Reset,
      users, // 返回 users 供下拉使用
      handlePageChange,
      handleTabChange,
      Search,
      Export,
      selectedRows, // 返回 selectedRows 供导出使用
      handleSelectionChange // 返回 handleSelectionChange 供表格使用
    }
  }
};
</script>
<style scoped>
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
/* 添加一些间距和对齐样式 */
.el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 或者针对货品明细列特别处理 */
.el-table [label="货品明细"] .cell {
  padding: 0;
}
.el-table [label="货品明细"] .cell > div {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 8px 0;
}
.form-row .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}
.stats-box {
  display: flex;
  justify-content: space-around;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}
.statistics-container {
    display: flex;
    margin-bottom: 20px;
    gap: 20px;
    } 
.stat-group {
  display: flex;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  min-width: 0;
  text-align: center;      /* 添加此行 */
  justify-content: center; /* 如果 .stat-group 内部是 flex 布局，也居中子元素 */
  align-items: center;     /* 如果 .stat-group 内部是 flex 布局，也垂直居中子元素 */
}
.stat-group:first-child {
  flex: 0 0 30%;
}
.stat-group:last-child {
  flex: 0 0 65%;
  display: flex; /* 内部子元素横向排列 */
  justify-content: space-around; /* 子元素在主轴上均匀分布 */
  align-items: center; /* 子元素在交叉轴上居中 */
}
.stat-item h3 {
  color: #409eff;
  font-size: 24px;
  margin: 0;
}
.stat-item p {
  color: #606266;
  font-size: 14px;
  margin: 5px 0 0;
}
.action-buttons {
  text-align: left;
  margin-bottom: 20px;
}
/* 调整表格样式 */
.el-table {
  margin-top: 20px;
}
/* 货品明细列标题居中 */
.el-table .el-table__header-wrapper .el-table__header .gutter:last-of-type {
  display: none;
}
</style>